//
//  HWStatusPhotosView.m
//  01-黑马微博
//
//  Created by lanou3g on 15/9/16.
//  Copyright (c) 2015年 heima. All rights reserved.
//  cell上面的配图想注册

#import "HWStatusPhotosView.h"
#import "HWPhoto.h"
#import "HWStatusPhotoView.h"
#define HWStatusPhoneWH 70
#define HWStatusPhotoMargin 10
#define HWStatusPhotoMaxCol(count) ((count == 4)?2:3)
@implementation HWStatusPhotosView
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
    }
    return self;
}

- (void)setPhotos:(NSArray *)photos{
    _photos = photos;

    
    //创建足够数量的imageView
    while (self.subviews.count < photos.count) {
        HWStatusPhotoView *photoView = [[HWStatusPhotoView alloc] init];
        [self addSubview:photoView];
    }
   //便利imageView，设置图片
    for (int i = 0 ; i<self.subviews.count; i++) {
        //取出photoView
        HWStatusPhotoView *photoView = self.subviews[i];
        if (i < photos.count) {//显示
         //取出模型
            HWPhoto *photo = photos[i];
            photoView.hidden = NO;
            photoView.photo = photo;
        }else{
            photoView.hidden = YES;
        }
    }
}

- (void)layoutSubviews{
    [super layoutSubviews];
    //设置图片尺寸和位置
    NSInteger photosCount = self.photos.count;
    NSInteger maxCols = HWStatusPhotoMaxCol(photosCount);
    for (int i = 0; i<photosCount; i++) {
        HWStatusPhotoView *photoView = self.subviews[i];
        NSInteger col = i % maxCols;
        NSInteger row = i / maxCols;
        CGFloat photoX = col * (HWStatusPhoneWH + HWStatusPhotoMargin);
        CGFloat photoY = row * (HWStatusPhoneWH + HWStatusPhotoMargin);
        CGFloat photoWidth = HWStatusPhoneWH;
        CGFloat photoHeight = HWStatusPhoneWH;
        photoView.frame = CGRectMake(photoX, photoY, photoWidth, photoHeight);
    }
}

+ (CGSize)sizeWithCount:(NSInteger)count{
    //最大列数
   NSInteger maxCols = HWStatusPhotoMaxCol(count);
    //列数
    NSInteger cols = (count >=3)? 3 : count;
    CGFloat photosW = HWStatusPhoneWH * cols + HWStatusPhotoMargin * (cols - 1);
    //行数
    //    NSInteger rows = 0;
    //    if (count % 3 == 0) {// 3,6,9
    //        rows = count / 3;
    //    }else{//1,2,4,5,7,8
    //        rows = count / 3 + 1;
    //    }
    //    NSInteger rows = count / 3;
    //    if (count%3 != 0) {
    //        rows += 1;
    //    }
    NSInteger rows = (count + maxCols - 1) / maxCols;
    CGFloat photoH = HWStatusPhoneWH * rows + HWStatusPhotoMargin * (cols - 1);
    return CGSizeMake(photosW, photoH);
}

@end
